# -*- coding: utf-8 -*-
# =============================================================================
#     FileName: logger_demo.py
#         Desc: 演示使用Logging模块
#       Author: GGA
#        Email:
#     HomePage:
#      Version: 1.0.1
#   LastChange: 2020-12-20
#      History:
# =============================================================================

import logging
import logging.handlers
import os
import sys


class LoggerHelper(object):
    DEFAULT_LOGGER_NAME = "apps"
    DEFAULT_LOGGER_DIRS = "logs"

    @classmethod
    def init_logger(cls, logger_name=None, logger_level=logging.INFO):
        if logger_name is None or str(logger_name) == "":
            logger_name = cls.DEFAULT_LOGGER_NAME
        my_logger = logging.getLogger(logger_name)
        my_logger.setLevel(logging.DEBUG)
        # 设置格式
        logger_format = logging.Formatter("[%(asctime)s]-[%(levelname)s]: %(message)s")
        # 设置命令行类型日志
        sh = logging.StreamHandler(stream=sys.stdout)
        sh.setFormatter(logger_format)
        sh.setLevel(logger_level)
        my_logger.addHandler(sh)
        # 设置文件类型日志
        logger_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), cls.DEFAULT_LOGGER_DIRS)
        if not os.path.exists(logger_dir):
            os.makedirs(logger_dir)
        logger_file = os.path.join(logger_dir, "{}.log".format(logger_name))
        fh = logging.handlers.RotatingFileHandler(logger_file, maxBytes=50 * 1024 * 1024, backupCount=5)
        fh.setFormatter(logger_format)
        fh.setLevel(logger_level)
        my_logger.addHandler(fh)

    @classmethod
    def get_logger(cls, logger_name=None):
        if logger_name is None or str(logger_name) == "":
            logger_name = cls.DEFAULT_LOGGER_NAME
        return logging.getLogger(logger_name)


def logger_demo():
    app_name = "test_app"
    LoggerHelper.init_logger(
        logger_name=app_name,
        logger_level=logging.INFO
    )
    logger = logging.getLogger(app_name)
    logger.debug("this is debug message")
    logger.info("this is info message")
    logger.warning("this is warning info")


if __name__ == '__main__':
    logger_demo()
